/**
 *  This is a class to allow for use of arrays with the speed of primitive
 *  arrays, but the growability of vectors.
 */
package us.gaaoc.framework.util.collections;

/**
 *  This is a class to allow for use of arrays with the speed of primitive
 *  arrays, but the growability of vectors.
 *  
 *  Reference:
 *  <ul>
 *    <li> http://www.javaworld.com/javaworld/jw-08-1999/jw-08-cooltools.html?page=1 </li>
 *  </ul>
 *  
 * @author mcelratr
 *
 */
public class FastGrowableIntArray {
	    int sp = 0; // "stack pointer" to keep track of position in the array
	    private int[] array;
	    private int growthSize;
	    private static int defaultSize = 25;
	    
	    public FastGrowableIntArray()
	    {
	        this(defaultSize);
	    }
	    
	    public FastGrowableIntArray( int initialSize )
	    {
	        this( initialSize, (int)( initialSize / 4 ) );
	    }
	    
	    public FastGrowableIntArray( int initialSize, int growthSize )
	    {
	        this.growthSize = growthSize;
	        array = new int[ initialSize ];
	    }
	    public void add( int i )
	    {
	    	// If "stack pointer" larger than or equal to array size,
	    	// then create a new larger array.
	        if( sp >= array.length ) 
	        {
	            int[] tmpArray = new int[array.length + growthSize];
	            System.arraycopy( array, 0, tmpArray, 0, array.length );
	            array = tmpArray;
	        }
	        // After enlarging the array, if needed, add the value
	        array[sp] = i;
	        // And then increment the stack pointer
	        sp += 1;
	    }
	    public int[] toArray()
	    {
	        int[] trimmedArray = new int[ sp ];
	        System.arraycopy( array, 0, trimmedArray, 0, trimmedArray.length );        
	        return trimmedArray;
	    }

}
